<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      //封装Vue构造函数
      function Vue({ data }) {
        this._data = data;

        //  数据代理
        for (let key in this._data) {
          Object.defineProperty(this, key, {
            get: function ProxyGetter() {
              return this._data[key];
            },
            set: function ProxySetter(value) {
              this._data[key] = value;
            },
          });
        }

        observe(this._data);
      }

      //   function observe(data) {
      //     if (typeof data !== "object" || data === null) {
      //       return;
      //     }

      //     defineProperty(data);
      //   }

      //   function defineProperty(data) {
      //     for (let key in data) {
      //       let value = data[key];

      //       observe(value);

      //       Object.defineProperty(data, key, {
      //         get: function reactiveGetter() {
      //           console.log("获取数据劫持成功");
      //           return value;
      //         },
      //         set: function reactiveSetter(val) {
      //           console.log("修改数据劫持成功");
      //           value = val;
      //         },
      //       });
      //     }
      //   }

      // ---------------

      function observe(data) {
        if (typeof data !== "object" || data == null) {
          return;
        }

        defineProperty(data);
      }

      function defineProperty(data) {
        for (let key in data) {
          let value = data[key];

          observe(value);

          Object.defineProperty(data, key, {
            get: function reactiveGetter() {
              console.log("get");
              return value;
            },
            set: function reactiveSetter(val) {
              console.log("set");
              value = val;
            },
          });
        }
      }

      //实例化Vue
      const vm = new Vue({
        data: {
          name: "laowang",
          age: 18,
          sex: "男",
          score: {
            English: 120,
            Chinese: 119,
          },
        },
      });
      console.log(vm, "vm");
    </script>
  </body>
</html>
